package priv.blackbibo.application.service;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.util.Calendar;
import java.util.concurrent.locks.ReentrantLock;

import priv.blackbibo.application.R;
import priv.blackbibo.application.contants.Constants;

/**
 * Created by black on 2019-12-08.
 */
public class TimeCheckService extends Service {

    private static final String TAG = "TimeCheckService";

    private Integer secondsEveryRound = Constants.secondsPerRound;
    private Calendar endTimeCalendar;
    private Integer countdown;
    private Boolean isStart = false;
    private Boolean isEnd = true;
    private Boolean isInit = false;
    private CountdownThread countdownThread;
    private Activity main;
    private ReentrantLock statusLock = new ReentrantLock();

    public static final Integer JOB_START = 1;

    public TimeCheckService() {
        Log.d(TAG, "TimeCheckService: init");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");
        switch (action){
            case "restart":
                Log.d(TAG, "onStartCommand: restart");
            case "start":
                Log.d(TAG, String.format("onHandleIntent: start before isStart %s isEnd %s",isStart,isEnd));
                int countdownFromUser = intent.getIntExtra("countdown",Integer.valueOf(R.string.stop_time_default));
                if (isStart && !isEnd){
                    stopCountDown();
                }
                this.countdown = countdownFromUser;
                initConfiguration();
                startCountDown();
                Log.d(TAG, String.format("onHandleIntent: start finish isStart %s isEnd %s",isStart,isEnd));
                break;
            case "stop":
                Log.d(TAG, "onHandleIntent: stop");
                stopCountDown();
                break;
                default:
                    break;
        }
        return START_NOT_STICKY;
    }

    /**
     * 初始化信息
     */
    public void initConfiguration(){
        Calendar next = Calendar.getInstance();
        next.add(Calendar.SECOND,countdown * secondsEveryRound);
        endTimeCalendar = next;
        isInit = true;
    }

    /**
     * 通知更新组件
     */
    public void noticeForRefreshView(){
        Intent intent = new Intent(Constants.COUNT_DOWN_STATUS).putExtra("start",isStart).putExtra("end",isEnd);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    /**
     * 停止播放音乐和震动
     */
    public void stopNoticeUser(){
        Intent intent = new Intent();
        intent.putExtra("action","stop");
        sendBroadcast(intent);
    }

    /**
     * 开启线程
     */
    public void startCountDown(){
        if (!isInit){
            initConfiguration();
        }
        Log.d(TAG, String.format("startCountDown: before isStart %s isEnd %s", isStart,isEnd));
        if (isStart && isEnd){
            stopCountDown();
        }
        countdownThread  = new CountdownThread();
        countdownThread.start();
        try {
            statusLock.lock();
            isStart = true;
            isEnd = false;
        }finally {
            syncronizedStatus();
            statusLock.unlock();
        }
        Log.d(TAG, String.format("startCountDown: finish isStart %s isEnd %s", isStart,isEnd));
    }

    /**
     * 停止线程
     */
    public void stopCountDown(){
        Log.d(TAG, String.format("stopCountDown: before isStart %s isEnd %s",isStart,isEnd));
        if (isStart){
            try {
                statusLock.lock();
                countdownThread.interrupt();
                countdownThread = null;
                isStart = false;
                isEnd = true;
            }finally {
                syncronizedStatus();
                statusLock.unlock();
            }
        }
        Log.d(TAG, String.format("stopCountDown: finish isStart %s isEnd %s",isStart,isEnd));
    }

    public void resetCountDown(){
        if (isStart){
            stopCountDown();
        }
        if (isInit){
            endTimeCalendar = null;
        }
    }

    class CountdownThread extends Thread{
        @Override
        public void run() {
            for (;;){
                try {
                    Thread.sleep(490);
                    if (endTimeCalendar == null){
                        break;
                    }
                    Calendar nowCalendar = Calendar.getInstance();
                    try {
                        statusLock.lock();
                        if (nowCalendar.before(endTimeCalendar)){
                            isEnd = false;
                        }else {
                            isEnd = true;
                            endTimeCalendar = null;
                            break;
                        }
                    }finally {
                        syncronizedStatus();
                        statusLock.unlock();
                    }
                } catch (InterruptedException e) {
                    break;
                }finally {
                    noticeForRefreshView();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }

    public void syncronizedStatus(){
        SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.key_configuration), Context.MODE_PRIVATE);
        sharedPreferences.edit().putBoolean("isStart",isStart).apply();
        sharedPreferences.edit().putBoolean("isEnd",isEnd).apply();
    }
}
